package com.dingreading.cloud.admin.service.impl;

import com.dingreading.cloud.admin.dto.vo.BookLabelVO;
import com.dingreading.cloud.admin.entity.StoreBooks;
import com.dingreading.cloud.admin.entity.table.StoreBooksTableDef;
import com.dingreading.cloud.admin.mapper.StoreBooksMapper;
import com.dingreading.cloud.admin.service.StoreBooksService;
import com.dingreading.cloud.common.util.NepUtil;
import com.dingreading.cloud.common.util.PageUtil;
import com.mybatisflex.core.paginate.Page;
import com.mybatisflex.core.query.QueryCondition;
import com.mybatisflex.core.query.QueryMethods;
import com.mybatisflex.core.query.QueryOrderBy;
import com.mybatisflex.core.query.QueryWrapper;
import com.mybatisflex.core.row.BatchArgsSetter;
import com.mybatisflex.core.row.Db;
import com.mybatisflex.core.update.UpdateChain;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * 服务层实现。
 *
 * @author Administrator
 * @since 2023-11-22
 */
@Service
public class StoreBooksServiceImpl extends BaseServiceImpl<StoreBooksMapper, StoreBooks, StoreBooksTableDef> implements StoreBooksService {

    @Override
    protected StoreBooksTableDef getTable() {
        return StoreBooksTableDef.storeBooks;
    }

    @Override
    public Page<StoreBooks> pageList(PageUtil pageUtil, Long storeId, String keyword, Integer status,
                                     Long journalId, Long bookLabelId, Integer isbnStatus) {
        QueryCondition condition = QueryCondition.createEmpty();
        if (storeId != null) {
            condition.and(table.storeId.eq(storeId));
        }
        if (status != null) {
            condition.and(table.status.eq(status));
        }
        if (journalId != null) {
            condition.and(table.journalId.eq(journalId));
        }
        if (bookLabelId != null) {
            condition.and(table.bookLabelId.eq(bookLabelId));
        }
        if (StringUtils.isNotBlank(keyword)) {
            condition.and(table.bookName.like(keyword)
                    .or(table.isbn.like(keyword))
                    .or(table.author.like(keyword))
                    .or(table.bookNum.like(keyword)));
        }

        QueryOrderBy[] queryOrders = null;
        if (isbnStatus != null && isbnStatus > 0) {
            if (isbnStatus.equals(1)) {
                condition.and(table.isbn.isNull().or(table.isbn.eq("")));
            } else if (isbnStatus.equals(2)) {
                QueryWrapper wrapper = QueryWrapper.create()
                        .select(table.isbn)
                        .from(table)
                        .where(table.storeId.eq(storeId).and(table.isbn.isNotNull().and(table.isbn.ne(""))))
                        .groupBy(table.isbn)
                        .having(QueryMethods.count(table.isbn).gt(1));
                condition.and(table.isbn.in(wrapper));

                queryOrders = new QueryOrderBy[]{table.isbn.desc(), table.editTime.desc()};
            }
        }

        if (queryOrders == null || queryOrders.length == 0)
            queryOrders = new QueryOrderBy[]{table.status.desc(), table.id.desc(), table.editTime.desc()};

        QueryWrapper wrapper = QueryWrapper.create()
                .select(table.id, table.bookName, table.isbn, table.bookNum, table.author,
                        table.press, table.pubDate, table.bookLabelName, table.unitPrice, table.stockCount,
                        table.borrowCount, table.status, table.editTime)
                .from(table)
                .where(condition)
                .orderBy(queryOrders);

        return getMapper().paginateAs(Page.of(pageUtil.getPage(), pageUtil.getRows()), wrapper, StoreBooks.class);
    }

    @Override
    public List<StoreBooks> getByBooksId(Long bookId) {
        return getMapper().selectListByCondition(table.booksId.eq(bookId));
    }

    @Override
    public void updateStatus(Long id, Integer status) {
        UpdateChain.of(StoreBooks.class)
                .set(table.status, status)
                .where(table.id.eq(id))
                .update();
    }

    @Override
    public int dropBean(Long id) {
        return getMapper().deleteByCondition(table.id.eq(id));
    }

    @Override
    public void saveBatch(List<StoreBooks> list) {
        //批量转数组
        Db.executeBatch(list.size(), 500, StoreBooksMapper.class, (mapper, index) -> {
            StoreBooks books = list.get(index);
            mapper.insert(books);
        });
    }

    @Override
    public List<StoreBooks> getNoLabelName(Long storeId) {
        QueryCondition condition = QueryCondition.createEmpty();
        condition.and(table.storeId.eq(storeId))
                .and(table.bookLabelId.isNull());

        return getMapper().selectListByCondition(condition);
    }

    @Override
    public void updateLabelId(Long storeId, String isbn, Long bookLabelId, String bookLabelName) {
        QueryCondition condition = QueryCondition.createEmpty();
        condition.and(table.isbn.eq(isbn));
        if (storeId != null)
            condition.and(table.storeId.eq(storeId));

        UpdateChain.of(StoreBooks.class)
                .set(table.bookLabelId, bookLabelId)
                .set(table.bookLabelName, bookLabelName)
                .where(condition)
                .update();
    }

    @Override
    public int getStoreBookCnt(Long storeId) {
        QueryWrapper wrapper = QueryWrapper.create()
                .select(QueryMethods.sum(table.stockCount))
                .from(table)
                .where(table.storeId.eq(storeId));

        Integer integer = getMapper().selectObjectByQueryAs(wrapper, Integer.class);
        return NepUtil.nullToZero(integer);
    }

    @Override
    public void dbUpdateLabelInfoByIsbn(List<BookLabelVO> voList) {
        String sql = "update store_books set book_label_id=?, book_label_name=? where isbn=?";
        Db.updateBatch(sql, new BatchArgsSetter() {
            @Override
            public int getBatchSize() {
                return voList.size();
            }

            @Override
            public Object[] getSqlArgs(int index) {
                BookLabelVO vo = voList.get(index);
                Object[] args = new Object[3];
                args[0] = vo.getLabelId();
                args[1] = vo.getLabelName();
                args[2] = vo.getIsbn();
                return args;
            }
        });
    }

}
